package com.kotei;

import com.kotei.config.MyBatisPlusConfig;
import com.kotei.mapper.FarmhouseAttachmentMapper;
import com.kotei.mapper.ObsCompareMapper;
import com.kotei.pojo.FarmhouseAttachment;
import com.kotei.pojo.ObsCompare;
import org.apache.commons.collections4.ListUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 附件对比工具，需要按照梦梦姐要求预备好数据库 farmhouse_attachment
 */
public class VerifyFile {
    public static void main(String[] args) {

        startContrast(9L, 1000L);
    }


    public static void startContrast(Long startLine, Long count) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("开始时间\t" + sdf.format(new Date()));
        int corePoolSize = 8;    // 核心线程数
        int maxPoolSize = 16;    // 最大线程数
        long keepAliveTime = 9; // 空闲线程存活时间(秒)
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000); // 工作队列
        //15分钟 17.5W 第二次 开始时间	2025-05-21 11:50:13 2025-05-22 00:16:25
        ExecutorService customThreadPool = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );

        // 定义需要验证的目录,开始时间	2025-05-20 19:03:39 结束时间	2025-05-20 20:39:29
        String prefix = "X:\\ZFPT\\";

        // 获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = MyBatisPlusConfig.getSqlSessionFactory();

        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 获取Mapper
            FarmhouseAttachmentMapper farmhouseAttachmentMapper = session.getMapper(FarmhouseAttachmentMapper.class);
            List<FarmhouseAttachment> farmhouseAttachments = farmhouseAttachmentMapper.getAllList(startLine, 10L);
            System.out.println("数据总量\t" + farmhouseAttachments.size());
            // 列表分组
            List<List<FarmhouseAttachment>> partition = ListUtils.partition(farmhouseAttachments, 10000);
            for (int index = 0; index < partition.size(); index++) {
                List<FarmhouseAttachment> attachments = partition.get(index);
                Integer taskId = index;
                customThreadPool.execute(() -> {

                    try (SqlSession session1 = sqlSessionFactory.openSession(true)) {
                        ObsCompareMapper obsCompareMapper = session1.getMapper(ObsCompareMapper.class);
                        // 定义一千条数据写入一次，或者当前数据读到最后
                        List<ObsCompare> obsCompares = new ArrayList<>();
                        Iterator<FarmhouseAttachment> faIterator = attachments.iterator();
                        while (faIterator.hasNext()) {
                            FarmhouseAttachment attachment = faIterator.next();

                            String relativeAddressPath = attachment.getRelative_address_path();
                            String fileExplain = attachment.getFile_explain().replace("https://", "").replace(".obs.cn-north-4.myhuaweicloud.com:443", "")
                                    .replace(".obs.cn-north-4.myhuaweicloud.com", "").replace("/", "\\");
                            String path = prefix + fileExplain + relativeAddressPath;

                            // https://pegasus.obs.cn-north-4.myhuaweicloud.com:443/ATTACHMENTS/collect/
                            // 若仅需检查存在性，禁用冗余属性检查提升速度
                            boolean exists = Files.exists(Paths.get(path.replace("/", "\\")), LinkOption.NOFOLLOW_LINKS);

                            ObsCompare obsCompare = new ObsCompare();
                            obsCompare.setId(attachment.getId());
                            obsCompare.setFile_size(attachment.getFile_size());
                            obsCompare.setRelative_path(relativeAddressPath);
                            obsCompare.setModule("cj");
                            obsCompare.setTime(new Date());
                            if (!exists) {
                                obsCompare.setAbsolute_path(attachment.getFile_explain() + relativeAddressPath);
                                obsCompare.setExist(0);
                            } else {
                                obsCompare.setAbsolute_path(path);
                                obsCompare.setExist(1);
                            }
//                            obsCompareMapper.insertObsCompare(obsCompare);
                            obsCompares.add(obsCompare);

                            // 数据堆积达到一千条或者数据读取完毕开始写入数据库
                            if (obsCompares.size() == 1000 || !faIterator.hasNext()) {
                                obsCompareMapper.insertObsCompareList(obsCompares);
                                obsCompares.clear();
                                int i = atomicInteger.incrementAndGet();
                                System.out.println(String.format("写入\t%s\t%d", Thread.currentThread().getName(), i));
                            }

//                            System.out.println(String.format("写入\t%s\t%d\t%d\t%s", Thread.currentThread().getName(), taskId, i, obsCompare.getId()));
                        }
                        System.out.println("结束时间\t" + sdf.format(new Date()));
                        session1.close();
                    }
                });

            }
            session.close();
        }
    }
}